package com.jinlejia.bbs.ui.fun;

import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.jinlejia.bbs.R;
import com.jinlejia.bbs.bean.db.BbsSearchHistoryBean;
import com.jinlejia.bbs.databinding.BbsActivitySearchBinding;
import com.jinlejia.bbs.logic.SearchLogic;
import com.jinlejia.erp.utils.DbUtil;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;

import java.util.ArrayList;
import java.util.List;

public class BBSSearchActivity extends AppCompatActivity implements SearchLogic.LogicCallBack {
    private BbsActivitySearchBinding binding;
    private SearchLogic logic;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.bbs_activity_search);
        binding.setEvent(this);
        logic = new SearchLogic(this,this);
        binding.cancelTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish("");
            }
        });
        binding.closeImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.searchEditText.setText("");
            }
        });
        binding.searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_SEARCH){
                    String tagStr = v.getText().toString();
                    if (!TextUtils.isEmpty(tagStr)){
                        saveHistoryToDB(tagStr);
                        finish(tagStr);
                    }
                }
                return false;
            }
        });
        binding.searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()==0){
                    binding.closeImageView.setVisibility(View.GONE);
                }else {
//                    binding.closeImageView.setVisibility(View.VISIBLE);
                }
            }
        });
        initView();
    }

    private void initView() {
        logic.execute();
        initHistory();
    }

    @Override
    public void onResult(List<String> result) {
        initHot(result);
    }

    private void initHot(List<String> list) {
        int max = list.size()>4?4:list.size();
        if (max==0){
            binding.hotLayout.setVisibility(View.GONE);
        }else {
            binding.hotLayout.setVisibility(View.VISIBLE);
        }
        TextView [] views = new TextView[]{binding.hotText1,binding.hotText2,binding.hotText3,binding.hotText4};
        for (int i = 0; i < max; i++) {
            String s = list.get(i);
            views[i].setVisibility(View.VISIBLE);
            views[i].setText(s);
        }
    }

    public void selectHistoryEvent(View view){
        TextView textView = (TextView) view;
        String text =textView.getText().toString();
        saveHistoryToDB(text);
        finish(text);
    }


    public void selectHotEvent(View view){
        TextView textView = (TextView) view;
        String text =textView.getText().toString();
        saveHistoryToDB(text);
        finish(text);
    }

    private void initHistory() {
        List<String> list = searchHistoryFromDB();
        int max = list.size()>4?4:list.size();
        if (max==0){
            binding.historyLayout.setVisibility(View.GONE);
        }else {
            binding.historyLayout.setVisibility(View.VISIBLE);
        }
        TextView [] views = new TextView[]{binding.historyText1,binding.historyText2,binding.historyText3,binding.historyText4};
        for (int i = 0; i < max; i++) {
            String s = list.get(i);
            views[i].setVisibility(View.VISIBLE);
            views[i].setText(s);
        }
    }

    private void finish(String text){
        Intent data = new Intent();
        data.putExtra("name",text);
        setResult(RESULT_OK,data);
        finish();
    }



    //region 显示历史数据
    private void saveHistoryToDB(String text){
        QueryBuilder<BbsSearchHistoryBean> builder = QueryBuilder.create(BbsSearchHistoryBean.class);
        ArrayList<BbsSearchHistoryBean> list = DbUtil.getDB(this).single().query(builder);
        if (list != null && list.size()>4){ //删除历史上限
            DbUtil.getDB(this).single().delete(list.get(0));
        }
        if (DbUtil.getDB(this).single().query(new QueryBuilder<>(BbsSearchHistoryBean.class)
                .whereEquals("name", text)).size() == 0) {
            //不包含，直接存
            DbUtil.getDB(this).single().save(new BbsSearchHistoryBean(text));
        } else {
            //已经存在，先删除再存
            DbUtil.getDB(this).single().delete(WhereBuilder.create(BbsSearchHistoryBean.class, "name=?", new String[]{text}));
            DbUtil.getDB(this).single().save(new BbsSearchHistoryBean(text));
        }
    }

    private List<String> searchHistoryFromDB(){
        QueryBuilder<BbsSearchHistoryBean> builder = QueryBuilder.create(BbsSearchHistoryBean.class);
        builder.appendOrderDescBy("id");
        ArrayList<BbsSearchHistoryBean> list = DbUtil.getDB(this).single().query(builder);
        ArrayList<String> texts = new ArrayList<>();
        if (list!=null){
            for (BbsSearchHistoryBean bean:list) {
                texts.add(bean.getName());
            }
        }
        return texts;
    }

}
